import requests
import re
import json


def debug_response(response):
    print("\n======= DEBUG START =======")
    print(f"状态码: {response.status_code}")
    print("响应头:", response.headers)
    print("响应内容:", response.text[:500])
    print("======= DEBUG END =======\n")


def get_douyin_video_url(share_url):
    headers = {
        "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",
        "Referer": "https://www.douyin.com/",
        "Cookie":'your_cookie_here'
    }

    try:
        # === 第一步：获取视频ID ===
        response = requests.get(share_url, headers=headers, allow_redirects=True)
        final_url = response.url
        print(f"重定向后URL: {final_url}")

        # 新正则匹配规则
        video_id_match = re.search(r'/video/(\d+)|/share/video/(\d+)', final_url)
        if not video_id_match:
            print("无法提取视频ID")
            return None

        # 获取第一个非空分组
        video_id = video_id_match.group(1) or video_id_match.group(2)
        print(f"解析到视频ID: {video_id}")

        # === 第二步：构造带签名的API请求 ===
        api_url = f"https://www.douyin.com/aweme/v1/web/aweme/detail/?aweme_id={video_id}"

        response = requests.get(api_url, headers=headers)
        debug_response(response)
        # === 第三步：处理响应数据 ===
        if response.status_code != 200:
            print(f"接口请求失败，状态码: {response.status_code}")
            return None

        try:
            data = response.json()
        except json.JSONDecodeError:
            print("响应不是有效的JSON格式")
            return None

        # 调试：打印数据结构
        print("API响应结构:", json.dumps(data, indent=2, ensure_ascii=False)[:1000])

        # === 第四步：提取无水印地址 ===
        if data.get('aweme_detail'):
            video_info = data['aweme_detail']['video']

            # 最新无水印地址路径（2024年7月验证）
            clean_url = video_info['play_addr']['url_list'][0].replace('playwm', 'play')
            return clean_url

        return None

    except Exception as e:
        print(f"处理错误: {e}")
        return None


# 测试
share_url = "https://v.douyin.com/XK2Ky3VIHb4/"
video_url = get_douyin_video_url(share_url)
print("最终地址:", video_url)